<?php
declare (strict_types=1);

namespace app\common\model;

use app\common\facade\Target;
use app\common\model\Statistics as StatisticsModel;

/**
 * @mixin \think\Model
 */
class Relation extends Base
{

    protected $name = 'user_relation';

    public function getAll($param)
    {
        try {

            return $this->where($param)->select()->toArray();

        } catch (\Exception $e) {
            return [];
        }
    }

    public function getCreateTimeAttr($value)
    {
        return date('Y-m-d', intval($value));
    }

    protected function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,level_id,team_id,my_income');
    }

    protected function fresh()
    {
        return $this->hasOne(User::class, 'id', 'new_uid')
            ->field('id,code,nickname,mobile,team_id,team_total');
    }


    /**
     * 原点 2020年8月22日16:25:27 记录推荐关系
     *
     * @param $uid -- 新会员ID
     * @param $code -- 新会员编号
     * @param $status -- 状态：默认0普通会员1正式会员
     * @param $parent_code -- 推荐人的编号
     * @return array
     */
    public function record($uid, $code, $parent_code, $parent_id, $status = 0)
    {
        try {
            $algebra = 1;
            $time = time();
            if ($parent_code) {
                $p_code = $parent_code;
                $insert = [];
                while ($parent = User::where('code', $p_code)->field('id,code,parent_code')->find()) {
                    if ($parent) {
                        $data['uid'] = $parent->id;
                        $data['code'] = $parent->code;
                        $data['create_time'] = $time;
                        $data['new_uid'] = $uid;
                        $data['new_code'] = $code;
                        $data['first_uid'] = $parent_id;
                        $data['first_code'] = $parent_code;
                        $data['algebra'] = $algebra;
                        $data['create_time'] = $time;
                        $data['status'] = $status;
                        $insert[] = $data;
                        $p_code = $parent->parent_code;
                    }
                    $algebra++;
                }
                $this->saveAll($insert);
            }
            return ['code' => 1, 'msg' => '操作成功'];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }

    /**
     * @param $amount - 金额
     * @param $uid - 会员ID
     * @param string $key - 团队业绩key
     * 原点 2021年12月28日11:50:17 更新团队业绩
     */
    public static function renewTeamTotal($amount, $uid, $key = 'team_total')
    {
        $all_id = parent::where('new_uid', $uid)->column('uid');
        if (!empty($all_id)) {
            User::whereIn('id', $all_id)->inc($key, floatval($amount))->update();
        }

    }


    //升级
    public static function upgrade($uid): array
    {
        try {
            $list = parent::where('new_uid', $uid)->with('user')->field('id,uid')->select();//用户上级
            foreach ($list as $item) {
                    $level = TeamLevel::where('amount', '<=', $item->user->my_income)->order('id','desc')->find();
                    if (!$level) continue;
                    if($item->user->team_id<$level->id)
                    {
                        User::update(['team_id' => $level->id], ['id' => $item->uid]);
                    }
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    //分享收益
    public static function share_reward($uid,$amount,$order_type)
    {
        $share_reward = 'share_reward_'.$order_type;
        $share_reward = cache('system')[$share_reward];
        $list = parent::where('new_uid', $uid)->with('user')->field('id,uid')->select();//用户上级
        $num=0;
        foreach ($list as $item) {
//            $amount = bcmul((string)$amount, (string)$share_reward, 2);//
            if($item->user->level_id>1)
            {
                $amount = round($amount*$share_reward, 2);
                if($amount<1) break;
                Target::Account()
                    ->basics($item->uid, 'integral', $amount, '分享收益', '+')
                    ->lock(false)//写入流水是否上锁，默认false,开启后会大幅降低性能，开启后必须配合事务使用
                    ->createBonus($uid, '2');
                User::where('id', $item->uid)->inc('my_income', floatval($amount))->update();//累计收入
                $uid = $item->uid;
                $num+=0;
            }

        }
        StatisticsModel::_update($num, 'expend');
    }



    //管理收益
    public static function manage_income($uid,$amount)
    {
        $list = parent::where('new_uid', $uid)->with('user')->field('id,uid')->select();//用户上级
        $bonus = 0;
        $num = 0;
        foreach ($list as $item) {
            if($item->user->level_id>1)
            {
                $level = TeamLevel::find($item->user->team_id);
                if($level)
                {
                    if($level->bonus>$bonus)
                    {
                        $bonus_amount = $level->bonus-$bonus;
                        $amounts = round($amount*$bonus_amount, 2);//
                        Target::Account()
                            ->basics($item->uid, 'integral', $amounts, '管理收益', '+')
                            ->lock(false)//写入流水是否上锁，默认false,开启后会大幅降低性能，开启后必须配合事务使用
                            ->createBonus($uid, '3');
                        User::where('id', $item->uid)->inc('my_income', floatval($amounts))->update();//累计收入
                        $bonus = $level->bonus-$bonus;
                        $num+=$amounts;
                    }

                }
            }

        }
        StatisticsModel::_update($num, 'expend');
    }

}
